(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name webApp.controller:MainCtrl
     * @description
     * # MainCtrl
     * Controller of the webApp
     购买controller
     */
    angular.module('webApp')
        .controller('BuyCrtl', BuyCrtl);

    BuyCrtl.$inject = ['$scope', 'dataService','helper','$rootScope','$timeout','$state','$location','$window','$interval'];

    function BuyCrtl($scope, dataService,helper,$rootScope,$timeout,$state,$location,$window,$interval) {
             
            $scope.listAction=function(){
            	$scope.cartIds=	$location.search().cart;
                $scope.address_id=$location.search().address_id;
                $scope.buy_imdy=$location.search().buy_imdy;
                // return false;
                if($scope.buy_imdy){
                  $scope.buy_item_id=jQuery.parseJSON($scope.buy_imdy).item_id;
                }
                $scope.buy_Total=0;
                var url2="";
                var addressStatus=true;
               $rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
                    $rootScope.previousState = from;
                    $rootScope.previousParams = fromParams;
               });
               if($state.current.name=="buy.add"){
                  dataService.addressGet().then(function(address){
                        if(address.Msg){

                        }else{
                           if(address.deliver_addrs.length==0&&$rootScope.previousState&&$rootScope.previousState.name=="address.add"){
                              helper.toast("缺少收货地址无法完成下单","text");
                               if($scope.cartIds){
                                  url2="#/shoppingcart/list";
                                }else if($scope.buy_imdy){
                                  url2="#/item/info?item_id="+angular.fromJson($scope.buy_imdy).item_id;
                                }
                              location.href=url2;
                            }else{
                              console.log("11111");
                            if(_.size(address.deliver_addrs)<=0){
                              var url1="";
                              if($scope.cartIds){
                                url1="#/address/add?carts="+$scope.cartIds;
                                url2="#/cart/list";
                              }else if($scope.buy_imdy){
                                url1="#/address/add?buy_imdy="+angular.toJson($scope.buy_imdy);
                                url2="#/item/info?item_id="+angular.fromJson($scope.buy_imdy).item_id;
                              }
                              helper.myAlert2("你还没有默认收货地址，请设置收货地址",url1,url2);
                            }else{
                              async.map(address.deliver_addrs,function(address_info,callback){
                                if($scope.address_id){
                                  if($scope.address_id==address_info.address_id){
                                    $scope.order_address=address_info;
                                  }
                                }else{
                                  if(!$scope.order_address){
                                    // $scope.order_address=address_info;
                                  }
                                  if(address_info.is_default==1){
                                    $scope.order_address=address_info;
                                  }
                                }
                                callback(null,null)
                              },function(e,r){
                                 if(!$scope.order_address){
                                    helper.myAlert("请设置默认收货地址");
                                    if($scope.buy_imdy){
                                     location.href="#/buy/choice?buy_imdy="+angular.toJson($scope.buy_imdy);
                                    }else{
                                     location.href="#/buy/choice?cart="+angular.toJson($scope.cartIds);
                                    }
                                  }
                              });
                            }
                          }
                        }
                  });
                }

              if($scope.cartIds){
                $scope.getCartData($scope.cartIds);
              }
              if($scope.buy_imdy){
                 $scope.buy_imdy=jQuery.parseJSON($scope.buy_imdy);
                $scope.sku_id=$scope.buy_imdy["sku_id"];
                $scope.item_id=$scope.buy_imdy["item_id"];
                $scope.quantity=$scope.buy_imdy["quantity"];
                dataService.itemOne($scope.item_id).then(function(result){
                  var data={};
                  var buy_para={};
                  buy_para[$scope.sku_id+""]=$scope.quantity;
                  data["buy_para"]=buy_para;
                  // data["payment_opt"]=0;
                   if($scope.order_address){
                    data.deliver_name=$scope.order_address.real_name;
                    data.deliver_phone=$scope.order_address.mobile;
                    data.deliver_address=$scope.order_address.area_info+" "+$scope.order_address.address
                  }
                  dataService.buystep1(data).then(function(orderPriceview){
                      $scope.buy_order=orderPriceview;
                      $scope.buy_order.item=result;
                      $scope.buy_order.quantity=$scope.quantity;
                      async.map($scope.buy_order.item.skus,function(sku){
                        if(sku.sku_id==$scope.sku_id){
                          sku.sku_checked=true
                        }
                      })
                  });
                });
              }
              $scope.$watch('buy_order.quantity',function(newV,old){
                // if(newV){
                //   $scope.buy_Total=0;
                //   _.map($scope.buy_order.items,function(item){
                //     $scope.buy_Total+=item.price*$scope.buy_order.quantity;
                //   });
                // }
                  if(newV!=old){
                      var data={};
                      var buy_para={};
                      buy_para[$scope.buy_imdy.sku_id+""]=newV;
                      data["buy_para"]=buy_para;
                      // data["payment_opt"]=0;
                       if($scope.order_address){
                        data.deliver_name=$scope.buy_order.deliver_name;
                        data.deliver_phone=$scope.buy_order.deliver_phone;
                        data.deliver_address=$scope.buy_order.deliver_address;
                      }
                      dataService.itemOne($scope.buy_imdy.item_id).then(function(item){
                          dataService.buystep1(data).then(function(result){
                            // $scope.buy_order=null;
                            // $scope.buy_order.items=result.items;
                            $scope.buy_order.item=item;
                            $scope.buy_order.total_fee=result.total_fee;
                            $scope.buy_order.pay_fee=result.pay_fee;
                            $scope.buy_Total=$scope.buy_order.total_fee;
                            $scope.pay_fee=$scope.buy_order.pay_fee;
                          _.map($scope.buy_order.item.skus,function(sku){
                            if(sku.sku_id==$scope.sku_id){
                              sku.sku_checked=true
                              sku.skus_propertie_name="";
                              async.map(sku.sku_properties.split(";"),function(skus_propertie){
                                if($.trim(skus_propertie)){
                                  var sku_key= skus_propertie.split(":");
                                 sku.skus_propertie_name+=sku_key[2]+":"+sku_key[3]+";";
                                }
                              });
                            }
                          });
                              // $scope.buy_order.quantity=$scope.quantity;

                          _.map(result.items,function(item){
                            if(item.sku_id==$scope.sku_id){
                              $scope.buy_order.items[0].quantity=item.quantity;
                              $scope.buy_order.items[0].price=item.price;
                              $scope.buy_order.items[0].fee=item.fee;
                              // $scope.quantity=  item.quantity;

                            }
                          })
                          });
                      });
                      console.log("buy_order",$scope.buy_imdy,$scope.buy_order,newV);
                  }
                });
            }
            $scope.getCartData=function(cartIds){
                $scope.shop={};
            	$scope.buy={};
                $scope.order=null;
                $scope.goods_total=0;
                // $scope.payment_opt=-1;
                var carts_shop_id=null;
                if(_.isObject(cartIds)){
                 carts_shop_id =angular.toJson(cartIds);

                }else{
                 carts_shop_id =angular.fromJson(cartIds);

                }

                var index=0;
                _.map(carts_shop_id,function(shop_id,cart_item_id){
                    dataService.cartGet({shop_id:shop_id}).then(function(carts){
                      var cartIndex=0;
                        if(_.size(carts.cart_items)==0){
                          index++;
                        }
                        _.map(carts.cart_items,function(cart){
                            if(cart.cart_item_id==cart_item_id){
                                 var orderItem={};
                                    if(!$scope.shop[cart.shop_id]){
                                        $scope.shop[cart.shop_id]={};
                                        $scope.shop[cart.shop_id].items=[];
                                        $scope.shop[cart.shop_id].note=null;
                                        // $scope.shop[cart.shop_id].payment_opt=0;
                                    }
                                 dataService.itemOne(cart.item_id).then(function(result){
                                     var skuIndex=0;
                                     async.map(result.skus,function(sku,callback){
                                         if(sku.sku_id==cart.sku_id){
                                                sku.sku_checked=true;
                                         }
                                         var skus_properties_array=sku.sku_properties.split(";");
                                          sku.skus_propertie_name="";
                                          _.map(skus_properties_array,function(skus_propertie){
                                            if($.trim(skus_propertie)){
                                              var sku_key= skus_propertie.split(":");
                                              sku.skus_propertie_name+=sku_key[2]+":"+sku_key[3]+";";
                                            }
                                          });
                                         skuIndex++;
                                         callback(null,null);
                                     },function(e,r){
                                         orderItem.item=result;

                                         orderItem.quantity=cart.quantity;
                                         $scope.goods_total+=cart.quantity*result.price;
                                         $scope.shop[cart.shop_id].items.push(orderItem);

                                     });
                                      index++;
                                      if(index==_.size(carts_shop_id)){
                                        $timeout(function(){
                                          if(_.size($scope.shop)==0){
                                            $location.url("shoppingcart/list");
                                          }else if(_.size($scope.shop)>0){
                                          $scope.previewAdd();
                                          }
                                        });
                                      }
                                 });
                                
                             }
                                cartIndex++;
                              $timeout(function(){

                             if(cartIndex==_.size(carts.cart_items)&&_.size($scope.shop)==0){
                               index++;
                             }
                           });
                         })
                         if(index>0){
                          $timeout(function(){
                            if(_.size($scope.shop)==0){
                            //   $location.url("shoppingcart/list");
                            }
                          })
                         }
                    });
                   
                })

            }
            $scope.buy_imdyPreviewAdd=function(){
              dataService.buystep1(order).then(function(result){
                  if(result.Msg){
                      helper("error:"+result.Msg);
                  }else{
                      $scope.order=result;
                  }
              });
            }
            $scope.previewAdd=function(){
                  var orders=[];
                  async.map($scope.shop,function(shop,callbackshop){
                      var order={};
                      order.buy_para={};
                      $timeout(function(){
                          async.map(shop.items,function(item,callback){
                              _.map(item.item.skus,function(sku){
                                  if(sku.sku_checked){
                                         order.buy_para[sku.sku_id]=item.quantity;
                                  }
                              })
                              callback(null,null);
                          },function(e,r){
                              order.note="";
                              orders.push(order);
                          });
                          callbackshop(null,null);
                      })
                  },function(e,r){
                      _.map(orders,function(order){
                            // if(order.payment_opt==-1){
                            //   return false;
                            // }
                              if($scope.order_address){
                                order.deliver_name=$scope.order_address.real_name;
                                order.deliver_phone=$scope.order_address.mobile;
                                order.deliver_address=$scope.order_address.area_info+" "+$scope.order_address.address
                              }
                              dataService.buystep1(order).then(function(result){
                                  if(result.Msg){
                                      helper("error:"+result.Msg);
                                  }else{
                                      $scope.buy_Total=result.total_fee;
                                      $scope.pay_fee=result.pay_fee;
                                      $scope.order=result;
                                  }
                              });
                      })
                  });
            }
            $scope.confirmOrder=function(){
                  if($scope.shop){
                      var orders=[];
                    async.map($scope.shop,function(shop,callbackshop){
                        var order={};
                        order.buy_para={};
                        async.map(shop.items,function(item,callback){
                            _.map(item.item.skus,function(sku){
                                if(sku.sku_checked){
                                      order.buy_para[sku.sku_id]=item.quantity;
                                }
                            })
                            callback(null,null);
                        },function(e,r){
                            // order.payment_opt=shop.payment_opt;
                            order.note=shop.note;

                            orders.push(order);
                        })
                        callbackshop(null,null);
                    },function(e,r){
                        _.map(orders,function(order){
                          // 
                              if($scope.order_address){
                                order.deliver_name=$scope.order_address.real_name;
                                order.deliver_phone=$scope.order_address.mobile;
                                order.deliver_address=$scope.order_address.area_info+" "+$scope.order_address.address
                              }
                               dataService.buystep2(order).then(function(result){
                                  if(result){
                                    var cartSettlement=angular.fromJson($scope.cartIds);
                                    _.map(cartSettlement,function(shop_id,cart_item_id){
                                        dataService.cartDelete(cart_item_id).then(function(r){
                                                if(r.Msg){
                                                    helper.myAlert("error:"+r.Msg);
                                                }else{
                                                }
                                        });
                                    })
                                    $location.url("buy/payconfirm?order_id="+result.order_id+"&url=details");
                                  }
                              });
                        })
                    });     
                }else if($scope.buy_order){
                  var data={};
                  var buy_para={};
                  buy_para[$scope.sku_id]=$scope.buy_order.quantity;
                  data.buy_para=buy_para;
                  data.note=$scope.buy_order.note;
                  // data.payment_opt=$scope.buy_order.payment_opt;
                  if($scope.order_address){
                    data.deliver_name=$scope.order_address.real_name;
                    data.deliver_phone=$scope.order_address.mobile;
                    data.deliver_address=$scope.order_address.area_info+" "+$scope.order_address.address
                  }
                  dataService.buystep2(data).then(function(result){
                    if(result.Msg){

                    }else{
                      $location.url("buy/payconfirm?order_id="+result.order_id+"&url=details");
                    }
                  });
                }           
            }
             
            $scope.payOrderAction=function(){
              var order_id= $location.search().order_id;
              $scope.pay={};
              $scope.payConfig={};
              $scope.pay["order_id"]=order_id;
              $scope.pay["pay_type"]=0;
              $scope.payWays=[{name:"微信",value:0,checked:true},
              {name:"支付宝",value:1,checked:false},]
              dataService.orderOne(order_id).then(function(order){
                $scope.payOrder=order;
              });
            }
    
            function onBridgeReady(){
               WeixinJSBridge.invoke(
                   'getBrandWCPayRequest',angular.fromJson($scope.payConfig.wxpay_rsp),
                   function(res){   
                   console.log("res",res);  
                      if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                        $timeout(function(){
                          $location.url("buy/paysuccess?order_id="+$scope.pay.order_id);
                        },300)
                       }   
                   }
               ); 
            }
            $scope.payConfirm=function(){
              dataService.paymentAdd($scope.pay).then(function(result){
                if(result.Msg){

                }else{
                  $scope.payConfig=result;
                      if (typeof WeixinJSBridge == "undefined"){
                       if( document.addEventListener){
                               document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);

                         }else if (document.attachEvent){
                             document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
                             document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                         }
                      }else{
                           onBridgeReady();
                      }
                }
              });
            }
            $scope.paysuccess=function(){
              $scope.success_order_id=$location.search().order_id;
              $scope.time=3;
              $interval(function(){
                $scope.time--;
                if($scope.time==0){
                  $location.url("order/details?order_id="+$scope.success_order_id);
                }
              },1000,$scope.time);
            }
            $scope.ordernumTab=function(buy_order,operator){
              if(operator=='+'){
                buy_order.quantity+=1;
              }else if(operator=='-'){
                buy_order.quantity-=1;
              }
            }
            //预览订单最中进入选择地址列表时的查询方法。
            $scope.initAddressList=function(){
                //传入预览订单需要参数。可以在跳入预览订单时保持预览订单初始化时数据

                $scope.carts=angular.fromJson( $location.search().cart);
                $scope.buy_imdy=$location.search().buy_imdy;
                $scope.addres_id=$location.search().address_id;
                if($scope.carts){
                  $scope.data=$scope.carts;
                }
                if($scope.buy_imdy){
                  $scope.data=$scope.buy_imdy;
                }
                dataService.addressGet().then(function(result){
                    $scope.addressList=result.deliver_addrs;
                });
            }   
            //修改支付方式
            $scope.checkedPayments=function(value,data){
                data.payment_opt=value;
            }
            //支付确认页的后退按钮方法
            $scope.cancelPay=function(){

              var url=$location.search().url;//用来判断后退时，返回的页面
              if(url=="list"){
                 helper.myAlert2("确定取消支付吗？","#/order/list",null);
              }else if(url=="details"){
                 helper.myAlert2("确定取消支付吗？","#/order/details?order_id="+$scope.payOrder.order_id,null);
              }
            }
            $scope.getChoiceAddress=function(){

            }
    }
})();